package com.itheima.controller;

import com.aliyuncs.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.bean.Orders;
import com.itheima.commons.R;
import com.itheima.dto.OrdersDto;
import com.itheima.dto.SetmealDto;
import com.itheima.service.OrdersService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Tang
 * @date 2023/1/12
 */
@Slf4j
@RequestMapping("/order")
@RestController
public class OrdersController {
    @Autowired
    private OrdersService ordersService;

    /**
     * 下单操作
     *
     * @param orders
     * @return
     */
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders) {
        //1.调用service的下单方法
        ordersService.submit(orders);
        //2.返回结果
        return R.success("下单成功！");
    }

    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String number, String beginTime, String endTime) {
        log.info("page = {},pageSize = {}", page, pageSize);

        //构造分页构造器
        Page<Orders> pageInfo = new Page(page, pageSize);

        //构造条件构造器
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        //添加过滤条件
        queryWrapper.like(number != null, Orders::getNumber, number);
        queryWrapper.ge(beginTime != null, Orders::getOrderTime, beginTime);
        queryWrapper.le(endTime != null, Orders::getOrderTime, endTime);
        //添加排序条件
        queryWrapper.orderByDesc(Orders::getCheckoutTime);

        //执行查询
        ordersService.page(pageInfo, queryWrapper);

        List<Orders> records = pageInfo.getRecords();
        records = records.stream().map((item) -> {

            item.setUserName("用户" + item.getUserId());

            return item;
        }).collect(Collectors.toList());

        return R.success(pageInfo);
    }

    //订单状态 1待付款，2待派送，3已派送，4已完成，5已取消
    @PutMapping
    public R<Orders> getUserOrder(@RequestBody Orders orders) {
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(orders.getId() != null, Orders::getId, orders.getId());
        Orders o = ordersService.getOne(wrapper);
        o.setStatus(orders.getStatus());
        ordersService.updateById(o);
        return R.success(o);
    }

    @GetMapping("/userPage")
    public R<Page<OrdersDto>> page(@RequestParam(defaultValue = "1") Integer page,
                                   @RequestParam(defaultValue = "1") Integer pageSize) {
        //1.调用service的分页查询
        Page<OrdersDto> ordersDtoPage = ordersService.findPage(page, pageSize);

        //2.返回分页查询结果
        return R.success(ordersDtoPage);
    }



}
